package cn.yedong.user.service.impl;

import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.jwt.JwtUtils;
import cn.yedong.basic.jwt.LoginData;
import cn.yedong.basic.jwt.RsaUtils;
import cn.yedong.basic.service.Impl.BaseServiceImpl;
import cn.yedong.basic.util.AjaxResult;
import cn.yedong.basic.util.HttpUtil;
import cn.yedong.basic.util.Md5Utils;
import cn.yedong.basic.util.StrUtils;
import cn.yedong.system.domain.Menu;
import cn.yedong.user.constant.WxConstants;
import cn.yedong.user.domain.Logininfo;
import cn.yedong.user.domain.User;
import cn.yedong.user.domain.Wxuser;
import cn.yedong.user.mapper.LogininfoMapper;
import cn.yedong.user.mapper.UserMapper;
import cn.yedong.user.mapper.WxuserMapper;
import cn.yedong.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 后台账号登陆
     * @param map
     * @return
     */
    @Override
    public Map<String, Object> loginAccount(Map<String, String> map) {
        String account = map.get("account");
        String checkPass = map.get("checkPass");
        //1.空值校验、
        if(StringUtils.isEmpty(account) || StringUtils.isEmpty(checkPass)){
            throw new BusinessException("信息不能为空！");
        }
        //2.账号校验
        Logininfo logininfo = logininfoMapper.findByAccount(account);
        if(logininfo == null){
            throw new BusinessException("账户名错误！");
        }
        //3.密码校验
        String dbPwd = logininfo.getPassword();
        String salt = logininfo.getSalt();
        String md5Pwd = Md5Utils.encrypByMd5(checkPass + salt);
        if(!dbPwd.equals(md5Pwd)){
            throw new BusinessException("密码错误！");
        }
        //4.状态校验
        if(!logininfo.getDisable()){
            throw new BusinessException("账号被禁用！");
        }
        //4.将用户信息存入redis过期时间30分钟，做登陆拦截使用
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        Map<String, Object> mapResult = new HashMap<>();
        mapResult.put("token",token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        mapResult.put("logininfo",logininfo);
        return mapResult;
    }

    /**
     * 前台微信登陆
     * @param map
     * @return
     */
    @Override
    public AjaxResult loginWechat(Map<String, String> map) {
        System.out.println("微信登陆请求——业务处理");
        //获取参数code
        String code = map.get("code");
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("亲，网络忙，请稍后再试！");
        }
        //组装url
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        //工具类发送请求
        String jsonStr = HttpUtil.httpGet(url);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        //处理返回的JSON数据：access_token 和openid
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        //根据openid查询wxuser判断是否绑定
        Wxuser wxuser = wxuserMapper.findByOpenId(openid);
        //绑定？注册？
        if(wxuser != null){
            User user = userMapper.loadById(wxuser.getUserId());
            if(user != null){
                //绑定且注册，将登录信息存入redis，30分钟有效-响应前端登录信息
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                String token = UUID.randomUUID().toString();
                redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("token",token);
                logininfo.setPassword(null);
                logininfo.setSalt(null);
                resultMap.put("logininfo",logininfo);
                return AjaxResult.me().setObj(resultMap);
            }
        }

        //不成功响应前端false;token和Logininfo
        return AjaxResult.me().setSuccess(false).setObj("?access_token="+access_token+"&openid="+openid);
    }

    /**
     * 微信绑定业务
     * @param map
     */
    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        //1.获取参数
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //2.参数空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode) || StringUtils.isEmpty(accessToken) || StringUtils.isEmpty(openId)){
            throw new BusinessException("信息不能为空");
        }
        //3.验证码过期校验
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if(obj == null){
            throw new BusinessException("验证码已过期！");
        }
        //4.验证码正确性校验
        if(!verifyCode.equals(obj.toString().split(":")[0])){
            throw new BusinessException("验证码错误！");
        }
        //5.组装url
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //6.发送请求，获取用户信息
        String jsonStr = HttpUtil.httpGet(url);
        System.out.println("微信官方返回的用户信息："+jsonStr);
        //7.将用户信息转换成【jsonStr2Wxuser】
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //8.判断是否注册user：【以前通过手机号码注册过没有绑定，可以根据手机号查询】
        User user = userMapper.findByPhone(phone);
        //8.1没有注册；注册，同步登陆信息【phone2user】【user2Logininfo】
        if(user == null){
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);
        }
        //8.2注册过，获取userId设置给wxuser
        wxuser.setUserId(user.getId());
        //9.添加wxuser
        wxuserMapper.add(wxuser);
        //10.将登陆信息存入redis
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30,TimeUnit.MINUTES);
        //11.返回前端token和logininfo
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        resultMap.put("logininfo",logininfo);

        return new AjaxResult().setObj(resultMap);
    }

    /**
     * 同步user到登录信息
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setDisable(true);
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 根据手机号码注册user
     * @param phone
     * @return
     */
    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPassword(phone);
        user.setState(1);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    /**
     * 将微信官方返回的用户信息转换成wxuser
     * @param jsonStr
     * @return
     */
    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setUnionid(obj.getString("unionid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        return wxuser;
    }

    /**
     * JWT登陆方案：根据登陆信息获取菜单和权限，用Map向前端传递菜单、权限、登陆信息(LoginData)、jwtToken
     * @param logininfo
     * @return
     */
    public Map<String,Object> jwtLogin(Logininfo logininfo){
        Map<String, Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        //设置【登录信息】：将登录信息密码和盐值置空，装进map和loginData
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        if(logininfo.getType() == 0){//只针对后台管理员做权限
            //设置【菜单和权限】：装进map和logininfo
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
        }
        //获取私钥
        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //
        return map;
    }
}
